package com.fjp.heartguard.ui.autograph

import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.os.Bundle
import androidx.lifecycle.lifecycleScope
import com.fjp.heartguard.app.Constants
import com.fjp.heartguard.app.base.BaseActivity
import com.fjp.heartguard.app.ext.showToast
import com.fjp.heartguard.databinding.ActivityAutographBinding
import com.fjp.heartguard.ui.question.QuestionActivity
import com.fjp.heartguard.viewmodel.AutographViewModel
import kotlinx.coroutines.launch
import me.hgj.jetpackmvvm.network.NetworkUtil
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

class AutographActivity : BaseActivity<AutographViewModel, ActivityAutographBinding>() {
    var path = ""
    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.viewModel = mViewModel
        mDatabind.proxy = ClickProxy()
        mViewModel.title.set("手写签名")
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.updateImageFailed.observe(this) {
            showToast("签名保存失败，请重新保存")
        }

        mViewModel.updateImageSuccess.observe(this) {
            val intent = Intent()
            intent.putExtra(Constants.INTENT_SINGLE_PATH,path)
            setResult(RESULT_OK,intent)
            finish()
        }
    }

    inner class ClickProxy {

        fun clickReWrite() {
            mDatabind.signaturePad.clear()
        }

        fun clickSave() {
            lifecycleScope.launch {
                path = saveBitmapToExternalCacheDir(baseContext, mDatabind.signaturePad.signatureBitmap, "${System.currentTimeMillis()}.png")
//                val path = saveBitmap2Document(mDatabind.signaturePad.signatureBitmap)
                if (path.isEmpty()) {
                    showToast("签名失败")
                    return@launch
                }
                if(NetworkUtil.isNetworkAvailable(this@AutographActivity)){
                    val file = File(path)

                    if (file.exists()) {
                        val index = file.name.lastIndexOf(".");
                        var fileType = file.name.substring(index + 1)
                        if (fileType == "jpg") {
                            fileType = "jpeg"
                        }

                        // 创建图片的Part
                        val reqFile = RequestBody.create(MediaType.parse("image/" + fileType), file)
                        val body = MultipartBody.Part.createFormData("file", file.name, reqFile)
                        mViewModel.updateSingle(body)

                    }
                }else{
                    QuestionActivity.olderInfo.signature = path
                    val intent = Intent()
                    intent.putExtra(Constants.INTENT_SINGLE_PATH,path)
                    setResult(RESULT_OK,intent)
                    finish()
                }


            }


        }
    }


    fun saveBitmap2Document(bitmap: Bitmap): String {
        val cacheDir = externalCacheDir
        if (cacheDir == null) {
            return ""
        }
        val file = cacheDir.resolve("${System.currentTimeMillis()}.png")
        if (!file.exists()) {
            val createResult = file.createNewFile()
            println(createResult)
        }
        var fos: FileOutputStream? = null
        try {
            // 创建要保存的PDF文件对象
            fos = openFileOutput(file.name, Context.MODE_PRIVATE)
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos)
            fos.flush()
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            fos?.close()
        }
        return file.path
    }

    private fun saveBitmapToExternalCacheDir(context: Context, bitmap: Bitmap, fileName: String): String {
        try {
            // 获取外部缓存目录
            val cacheDir = context.externalCacheDir
            if (cacheDir != null) {
                // 创建完整的文件路径
                val outputFile = File(cacheDir, fileName)
                // 打开文件输出流
                val fileOutputStream = FileOutputStream(outputFile)

                // 将 Bitmap 压缩并写入输出流
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream)

                // 刷新输出流
                fileOutputStream.flush()

                // 关闭输出流
                fileOutputStream.close()
                return outputFile.absolutePath
            }
        } catch (e: IOException) {
            e.printStackTrace()
            println("保存图片时出错: ${e.message}")
            return ""
        }
        return ""
    }
}